<template>

  <a-select
    showSearch
    labelInValue
    :disabled="disabled"
    :getPopupContainer="getPopupContainer"
    @search="loadData"
    :placeholder="placeholder"
    v-model="selectedAsyncValue"
    style="width: 100%"
    :filterOption="false"
    @change="handleAsyncChange"
    allowClear
    :notFoundContent="loading ? undefined : null"
  >
    <a-icon slot="suffixIcon" type="search" />
    <a-spin v-if="loading" slot="notFoundContent" size="small"/>
    <a-select-option v-for="d in options" :key="d.itemValue" :value="d.itemValue">{{ d.itemText }}</a-select-option>
  </a-select>

</template>

<script>
import debounce from 'lodash/debounce'
import { getAction } from '@/services/manage'
import Criteria from '@/utils/criteria'
import { OPERATOR } from '@/store/mutation-types'
export default {
  name: 'ZSearchSelectTag',
  props: {
    disabled: Boolean,
    value: [String, Number],
    url: String,
    optionText: String,
    optionValue: String,
    dictOptions: Array,
    placeholder: {
      type: String,
      default: '请选择',
      required: false
    },
    getPopupContainer: {
      type: Function,
      default: (node) => node.parentNode
    }
  },
  data() {
    this.loadData = debounce(this.loadData, 800)// 消抖
    this.lastLoad = 0
    return {
      loading: false,
      selectedValue: [],
      selectedAsyncValue: [],
      options: []
    }
  },
  watch: {
    'value': {
      immediate: true,
      handler(val) {
        if (!val) {
          if (val === 0) {
            this.initSelectValue()
          } else {
            this.selectedValue = []
            this.selectedAsyncValue = []
            this.options = []
          }
        } else {
          this.initSelectValue()
        }
      }
    }
  },
  methods: {
    initSelectValue() {
      if (!this.selectedAsyncValue || !this.selectedAsyncValue.key || this.selectedAsyncValue.key !== this.value) {
        // console.log('这才请求后台')
        const param = {}
        param[this.optionValue] = this.value // 根据编号精确搜索
        const queryParam = new Criteria()
        queryParam.addCriterions(param, OPERATOR.EQ) // 等于
        getAction(`${this.url}`, { criteria: queryParam.getEncode() }).then(res => {
          // console.log(res, 'res')
          if (res.success) {
            const obj = {
              key: this.value,
              label: ''
            }
            res.result.content.forEach(elem => {
              if (this.value === elem[this.optionValue]) {
                obj.label = elem[this.optionText]
                this.selectedAsyncValue = { ...obj }
                elem.itemText = elem[this.optionText]
                elem.itemValue = elem[this.optionValue]
                this.options = [elem]
              }
            })
          }
        })
      }
    },
    loadData(value) {
      // console.log('数据加载', value)
      this.lastLoad += 1
      const currentLoad = this.lastLoad
      this.options = []
      this.loading = true
      const param = {}
      param[this.optionText] = value // 根据名称模糊搜索
      const queryParam = new Criteria()
      queryParam.addCriterions(param, OPERATOR.LIKE) // like
      getAction(`${this.url}`, { criteria: queryParam.getEncode() }).then(res => {
        this.loading = false
        if (res.success) {
          if (currentLoad !== this.lastLoad) {
            return
          }
          res.result.content.forEach(elem => {
            elem.itemText = elem[this.optionText]
            elem.itemValue = elem[this.optionValue]
            this.options.push(elem)
          })
          // console.log('我是第一个', res)
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleAsyncChange(selectedObj) {
      this.selectedAsyncValue = selectedObj
      if (selectedObj) {
        this.selectedValue = selectedObj.key
        this.callback(selectedObj.key, selectedObj.label)
      } else {
        this.selectedValue = ''
        this.callback('', '')
      }
    },
    callback(key, label) {
      let selectedEle = {}
      this.options.forEach(elem => {
        if (elem.itemText === label && elem.itemValue === key) {
          selectedEle = elem
        }
      })
      this.$emit('change', key, label, selectedEle)
    }
  }
}
</script>
